<script setup lang="ts">
import { reactive, ref, watch, nextTick } from "vue";
import {
  ElAvatar,
  ElButton,
  ElCol,
  ElDrawer,
  ElForm,
  ElFormItem,
  ElInput,
  ElPagination,
  ElRow,
  ElTable,
  ElTableColumn,
} from "element-plus";
import useTable from "@/hooks/useTable";

import ApiActivity from "@/api/activity";
import ApiMerchant from "@/api/merchant";
import { ProSelect } from "@/modules/package/form";

const visible = defineModel<boolean>();

const { ids } = defineProps<{
  ids: string;
}>();

const emits = defineEmits<{
  selection: [event: any[]];
}>();

const fetchUrlMap = {
  id: ApiMerchant.merchantList,
  merchant_id: ApiActivity.activityApplyList,
};

const tableRef = ref();
const selectedMap = reactive(new Map());
const fetchUrl = ref(fetchUrlMap.id);

const search = reactive({
  merchant_title: "",
  act_id: undefined,
});
const { isFetching, list, pagination, execute, onFetchResponse } = useTable(
  fetchUrl,
  {
    immediate: false,
    defaultSearch: search,
  }
);

onFetchResponse(() => {
  nextTick(() => {
    list.value.forEach((row) => {
      if (selectedMap.get(row.id)) {
        tableRef.value!.toggleRowSelection(row, true);
      }
    });
  });
});

const setMapItem = (source: any) => {
  const id = source.id;
  selectedMap.set(id, { id, title: source.merchant_title });
};

watch(visible, (flag) => {
  if (flag) {
    if (ids) {
      const list = ids.split(",").map((id) => ({ id: +id, title: id }));
      list.forEach((e) => setMapItem(e));
    }

    execute();
  } else {
    selectedMap.clear();
  }
});

// 全选/取消全选
const handleSelectionAll = (selection: any[]) => {
  const isSelected = selection.length > 0;
  (isSelected ? selection : list.value).forEach((e) => {
    if (isSelected) {
      setMapItem(e);
    } else {
      selectedMap.delete(e.id);
    }
  });
};

// 选中/取消某一项
const handleSelection = (selection: any[], row: any) => {
  selection.forEach(setMapItem);
  const flag = selection.includes(row);
  if (!flag) {
    selectedMap.delete(row.id);
  }
};

// 确认
const handleConfirmSelection = () =>
  emits("selection", [...selectedMap.values()]);

const toSearch = () => {
  pagination.page = 1;
  execute();
};
</script>

<template>
  <ElDrawer size="50%" title="选择品牌" v-model="visible">
    <template #header>
      <div class="mr-3 -mb-7">
        <div class="mb-3 font-bold text-lg">选择品牌</div>

        <ElForm>
          <ElRow :gutter="16">
            <ElCol :span="10">
              <ElFormItem label="品牌名称">
                <ElInput
                  v-model="search.merchant_title"
                  placeholder="品牌名称"
                  clearable
                />
              </ElFormItem>
            </ElCol>

            <ElCol :span="10">
              <ElFormItem label="选择活动">
                <ProSelect
                  v-model="search.act_id"
                  :fetch-url="ApiActivity.activityList"
                  label-key="title"
                  value-key="id"
                  searchKey="title"
                  filterable
                  clearable
                  :fetch-options="{ size: 1000 }"
                />
              </ElFormItem>
            </ElCol>

            <ElCol :span="4">
              <ElFormItem>
                <ElButton type="primary" @click="toSearch">搜索</ElButton>
              </ElFormItem>
            </ElCol>
          </ElRow>
        </ElForm>
      </div>
    </template>

    <ElTable
      ref="tableRef"
      :data="list"
      height="calc(100vh - 220px)"
      v-loading="isFetching"
      @select="handleSelection"
      @select-all="handleSelectionAll"
    >
      <ElTableColumn type="selection" />
      <ElTableColumn label="品牌LOGO" width="100">
        <template #="{ row }">
          <ElAvatar :src="row.merchant_logo_png" />
        </template>
      </ElTableColumn>

      <ElTableColumn label="品牌名称" prop="merchant_title" />
      <ElTableColumn label="所在地址" prop="merchant_title">
        <template #="{ row }">
          {{ row.city }}
          {{ row.district }}
        </template>
      </ElTableColumn>
    </ElTable>

    <template #footer>
      <div class="flex justify-between">
        <ElButton type="primary" @click="handleConfirmSelection">确认</ElButton>

        <el-pagination
          background
          layout="prev, pager, next, total, sizes, jumpe"
          :total="pagination.total || 0"
          v-model:page-size="pagination.size"
          v-model:current-page="pagination.page"
        />
      </div>
    </template>
  </ElDrawer>
</template>
